package pl.edu.pw.polygen.core.project;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import pl.edu.pw.polygen.beans.ProjectBean;
import pl.edu.pw.polygen.beans.UserBean;
import pl.edu.pw.polygen.db.dao.ProjectDao;
import pl.edu.pw.polygen.db.dao.UserDao;
import pl.edu.pw.polygen.exception.ProjectExistException;

@Service("projectService")
public class ProjectServiceImpl implements ProjectService {
	
	@Autowired
	private ProjectDao projectDao;

	@Autowired 
	private UserDao userDao;

	public List<ProjectBean> getAllUserProjects(String userName) {
		UserBean userBean = userDao.getUserByName(userName);
		return projectDao.findAllByUser(userBean);
	}
	
	public ProjectBean updateProject(ProjectBean projectBean){
		return projectDao.saveProject(projectBean);
	}

	public ProjectBean createProject(String name, String description, String userName) throws ProjectExistException {
		UserBean user = userDao.getUserByName(userName);
		ProjectBean projectBean = new ProjectBean();
		projectBean.setName(name);
		projectBean.setDescription(description);
		projectBean.setUser(user);
		projectBean.setLastModification(new Date());
		if(projectDao.isExisting(projectBean)==false){
			return projectDao.createNewProject(projectBean);
		}else{
			throw new ProjectExistException("Project " + name + " already exist for user " + userName);
		}
	}
	
	public ProjectBean findProject(Long projectId) {
		return projectDao.findProject(projectId);
	}

	public void removeProject(String projectName, Long userId) {
		ProjectBean projectBean = projectDao.findProject(projectName,userId);
		projectDao.delete(projectBean);
	}

	public ProjectBean findProject(String projectName, Long userId) {
		ProjectBean projectBean = projectDao.findProject(projectName,userId);
		return projectBean;
	}
	
	
}
